import React from "react";
import { FlatList, Image, StyleSheet, Text } from "react-native";
import { TouchableOpacity, View } from "react-native-ui-lib";
import { commonStyles } from "../../configs/commonStyle";
import navigator from "../../utils/navigator";
import BasePage from "../BasePage";
import { IconImage } from "../../utils";
import NavigationBar from "../common/NavigationBar";
import ViewUtils from "../../utils/ViewUtils";
import DateFilter from "../components/DateFilter";
import { MapView, Marker } from "react-native-amap3d";
import moment from "moment";
import { inject, observer } from "mobx-react";
import ListSeparator from "../common/ListSeparator";
import ListEmpty from "../common/ListEmpty";
import ListFooter from "../common/ListFooter";
import { isAndroid } from "../../configs/platform";
import { call, uploadError } from "../../utils/util";

const INITIAL_REGION = {
  latitude: 22.616282489952997,
  longitude: 114.1345043622764,
  latitudeDelta: 0.1,
  longitudeDelta: 0.1,
};
/**
 * 订单地图
 */
@inject("userStore", "appStore")
@observer
export default class MapOrder extends BasePage {

  constructor(props) {
    super(props);
    this.pageNo = 1;
    this.pageSize = 15;
    this.totalPages = 0;
    this.isLoading = false;
    this.isFirst = true;
    this.state = {
      isRefreshing: false,
      showFoot: 0,
      showEmpty: false,
      dataList: [],
      delyStartTime: moment().format("YYYY-MM-DD"),
      delyEndTimeEnd: moment().format("YYYY-MM-DD"),
      centerLocation: null,
      showMap: true,
      optionList: [{
        label: "待配送",
        ordStates: [4, 5, 6],
        checked: true,
      },
        {
          label: "配送中",
          ordStates: [7],
          checked: true,
        }],
    };
  }

  componentDidMount() {
    super.componentDidMount();
    this.loadData(true);
  }

  loadData = (showLoading = false) => {
    const { dataList, delyStartTime, delyEndTimeEnd,optionList } = this.state;
    const { userInfo } = this.props.userStore;
    if (IsNullOrEmpty(delyStartTime)) {
      uploadError("queryOrder——map查询日期为空", `${delyStartTime},${delyEndTimeEnd}`);
    }
    let options=[];
    optionList.map((data)=>{
      if(data.checked)
      {
        options=[...options,data.ordStates]
      }
    })
    this.isLoading = true;
    let params = {
      pageNum: this.pageNo,
      pageSize: this.pageSize,
      token: global.token,
      // token: '6551245572408320',
      distributorId: userInfo.distributorId,
      ordStates: options.join(','),
      delyStartTime: `${delyStartTime} 00:00:00`,
      delyEndTimeEnd: `${delyEndTimeEnd} 23:59:59`,
      showLoading,
    };
    axios.get(api.queryOrder, { params })
      .then(res => {
        this.isLoading = false;
        logger("查询结果", res.list);
        let tempArr = [];
        let showf;
        this.totalPages = res.pages;
        if (this.pageNo == 1) {
          tempArr = res.list || [];
          showf = 0;
        } else {
          tempArr = dataList.concat(res.list);
          showf = (this.pageNo == this.totalPages) ? 1 : 0;
        }
        this.setState({
          //复制数据源
          dataList: tempArr,
          showFoot: showf,
          isRefreshing: false,
          showEmpty: (this.pageNo == 1 && tempArr.length == 0 ? true : false),
        });
        if (isAndroid() && this.isFirst == true && !IsNullOrEmpty(tempArr)) {
          this.isFirst = false;
          setTimeout(() => this._renderRefresh(false), 500);
        }
      })
      .catch(e => {
        logger("error", e);
        this.isLoading = false;
        this.setState({
          isRefreshing: false,
          showEmpty: (this.pageNo == 1 ? true : false),
        });
      });
  };

  _onEndReached = async () => {
    //如果是正在加载中或到底了，则返回
    if (this.state.showFoot != 0) {
      return;
    }
    //如果当前页大于或等于总页数，那就是到最后一页了，返回
    if (this.pageNo == this.totalPages || this.totalPages == 0) {
      return;
    } else {
      this.pageNo++;
    }
    //底部显示正在加载更多数据
    this.setState({ showFoot: 2 });
    //获取数据
    this.loadData(false);
  };

  // 下拉刷新
  _renderRefresh = (isRefreshing = true) => {
    // 不处于 下拉刷新
    if (this.isLoading === false && !this.state.isRefreshing) {
      this.setState({
        isRefreshing,
      });
      this.pageNo = 1;
      this.totalPages = 0;
      this.loadData();
    }
  };

  render_item = ({ item, index }) => {
    return (
      <TouchableOpacity activeOpacity={1} onPress={() => navigator.navigate("OrderDetails", { ordNo: item.ordNo })}>
        <View style={styles.titleWrap}>
          <Text style={commonStyles.text_black_14}>单号：{item?.xmbzNo}({item?.delySTime}-{item?.delyETime})</Text>
          <TouchableOpacity activeOpacity={1}
                            onPress={() => {
                              const { showMap } = this.state;
                              logger("移动到地图", item.addressLng);
                              if (!IsNullOrEmpty(item.addressLng) && parseFloat(item.addressLng) != 0) {
                                this.setState({
                                  showMap: !showMap, centerLocation: {
                                    latitude: parseFloat(item.addressLat),
                                    longitude: parseFloat(item.addressLng),
                                  },
                                });
                              }
                            }}>
            <Image source={IconImage.ic_location} style={{ width: 25, height: 25 }} />
          </TouchableOpacity>
        </View>
        <View style={styles.contentWrap}>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>分仓</Text>
            <Text style={commonStyles.text_black_13}>{item?.invoiceHeader}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>联系电话</Text>
            {
              item.cneeTel && !item.cneeTel.includes("*") ?
                <TouchableOpacity onPress={() => call(item?.cneeTel,item?.ordNo)}>
                  <Text style={commonStyles.text_black_13}>{item?.cneeTel}</Text>
                </TouchableOpacity>
                : <Text style={commonStyles.text_black_13}>{item?.cneeTel}</Text>
            }
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>地址</Text>
            <View marginL-10 flex right>
              <Text style={commonStyles.text_black_13}>{item?.address1}</Text>
            </View>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>商品</Text>
            <View marginL-10 flex right>
              {
                item.orderDetailList && item.orderDetailList.map(data => {

                  return (
                    <View row marginT-5>
                      <Text
                        style={commonStyles.text_black_13}>{data?.goodsName}（{data?.goodsSpecs}）(x{data?.num}）</Text>
                    </View>
                  );
                })
              }
            </View>
          </View>
        </View>
      </TouchableOpacity>
    );
  };

  renderMarker = () => {
    const { dataList } = this.state;
    const list = dataList.filter(data => !IsNullOrEmpty(data.addressLng) && parseFloat(data.addressLng) != 0 && !IsNullOrEmpty(data.addressLat) && parseFloat(data.addressLat) != 0);

    if (!IsNullOrEmpty(list)) {
      return list.map((data, index) => {
        let coordinate = {
          longitude: parseFloat(data.addressLng),
          latitude: parseFloat(data.addressLat),
        };
        // logger("是否选中", index==0);
        return (
          <Marker
            active={false}
            infoWindowDisabled={true}
            onPress={() => {
              logger("查看订单详情2", data.ordNo);
              navigator.navigate("OrderDetails", { ordNo: data.ordNo });
            }}
            position={coordinate}
          >
            <View centerH style={{ backgroundColor: "transparent" }}>
                <View style={styles.customInfoWindow}>
                  <View paddingH-7>
                    <Text style={commonStyles.text_white_12}>{data?.xmbzNo}</Text>
                  </View>
                  <View paddingH-7>
                    <Text style={commonStyles.text_white_12}>{data?.delySTime}-{data?.delyETime}</Text>
                  </View>
                </View>
                <Image source={IconImage.ic_location} style={{ width: 25, height: 25 }} />
              </View>
          </Marker>
        );
      });
    }
    return null;
  };

  renderMyMarker = () => {
    const { location } = this.props.userStore;
    // logger("更新位置", location);
    if (!IsNullOrEmpty(location) && location.latitude) {
      return (
        <Marker
          active={false}
          clickDisabled={false}
          infoWindowDisabled={true}
          icon={IconImage.icon_locate}
          position={{
            latitude: location.latitude,
            longitude: location.longitude,
          }}
        >
        </Marker>
      );
    }
    return null;
  };

  renderList = () => {
    const { dataList, isRefreshing } = this.state;
    return (
      <FlatList
        data={dataList}
        onRefresh={this._renderRefresh}
        showsVerticalScrollIndicator={false}
        refreshing={isRefreshing}
        extraData={this.state}
        style={{}}
        contentContainerStyle={{ flexGrow: 1 }}
        keyExtractor={(item, index) => "menu_" + index}
        renderItem={this.render_item}
        ItemSeparatorComponent={() => <ListSeparator height={0.5} backgroundColor={"#F7F7F7"} />}
        ListEmptyComponent={() => <ListEmpty showEmpty={this.state.showEmpty} />}
        onEndReached={this._onEndReached}
        onEndReachedThreshold={0.1}
        ListFooterComponent={() => <ListFooter showFoot={this.state.showFoot} page={this.pageNo} />}
        ListHeaderComponent={this.renderHeader}
      />
    );
  };


  render() {
    const { centerLocation, showMap, optionList, dataList } = this.state;
    const { location } = this.props.userStore;
    let center = null;
    // logger("中心位置", centerLocation);
    if (IsNullOrEmpty(centerLocation)) {
      if (!IsNullOrEmpty(dataList)) {
        const orderInfo = dataList.find(data => !IsNullOrEmpty(data.addressLng) && parseFloat(data.addressLng) != 0 && !IsNullOrEmpty(data.addressLat) && parseFloat(data.addressLat) != 0);
        // logger("订单详情", orderInfo);
        if (orderInfo) {
          center = {
            latitude: parseFloat(orderInfo.addressLat) || 22.616282489952997,
            longitude: parseFloat(orderInfo.addressLng) || 114.1345043622764,
          };
        } else {
          center = {
            latitude: 22.616282489952997,
            longitude: 114.1345043622764,
          };
        }
      } else {
        center = {
          latitude: location.latitude || 22.616282489952997,
          longitude: location.longitude || 114.1345043622764,
        };
      }

    } else {
      center = centerLocation;
    }

    return (
      <View useSafeArea style={commonStyles.body_primary}>
        <NavigationBar
          title={"订单地图"}
          backgroundColor={"transparent"}
          leftButton={ViewUtils.getLeftButton(() => this._onBackPress())}
          rightButton={ViewUtils.getRightTextBtn(showMap ? "切换列表" : "切换地图", () => this.setState({ showMap: !showMap }))}
        />
        <View style={commonStyles.container}>
          <View row centerV>
            <DateFilter onQueryClick={(delyStartTime, delyEndTimeEnd) => {
              this.setState({
                delyStartTime,
                delyEndTimeEnd,
              }, () => this.loadData(true));
            }} />
            <TouchableOpacity activeOpacity={1} throttleTime={1000} style={styles.btn}
                              onPress={() => this.loadData(true)}>
              <Text style={commonStyles.text_black}>刷新</Text>
            </TouchableOpacity>
          </View>
          {
            showMap == true ?
              <MapView
                showsCompass={false}
                ref={r => this.mapView = r}
                initialCameraPosition={{
                  target: center,
                  zoom: 12
                }}
                style={{ flex: 1 }}
              >
                {this.renderMarker()}
                {this.renderMyMarker()}
              </MapView>
              : this.renderList()
          }
          {
            showMap == true ?
              <TouchableOpacity style={{ position: "absolute", right: 10, bottom: 100 }} pointerEvents={"box-none"}
                                onPress={() => {
                                  if (location) {
                                    this.mapView.moveCamera({
                                      target: {
                                        latitude: location.latitude || 22.616282489952997,
                                        longitude: location.longitude || 114.1345043622764,
                                      },
                                      zoom: 16
                                    }, 1000)
                                  }
                                }}>
                <Image source={IconImage.icon_to_location} style={{ width: 32, height: 32 }} />
              </TouchableOpacity>
              : null
          }
          {
            showMap == true ?
              <View style={styles.selectWarp}>
                {
                  optionList.map((data, index) => {
                    return (
                      <TouchableOpacity style={styles.select_item} onPress={() => {
                        const tempList = optionList.map((item, pos) => {
                          if (index == pos) {
                            item["checked"] = !item.checked;
                          }
                          return item;
                        });
                        this.setState({ optionList: tempList },()=>this._renderRefresh(false));
                      }}>
                        <Image source={data.checked ? IconImage.btn_gx : IconImage.btn_wgx} style={styles.ckWrap} />
                        <Text style={commonStyles.text_black}>{data.label}</Text>
                      </TouchableOpacity>
                    );
                  })
                }
              </View>
              : null
          }
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  customInfoWindow: {
    backgroundColor: "#58A4F4",
    borderRadius: 2.5,
    elevation: 4,
    zIndex: 100,
    alignItems: "center",
  },
  iosCustomInfoWindow: {
    backgroundColor: "white",
    borderRadius: 2.5,
    elevation: 4,
    left: -50,
  },
  titleWrap: {
    justifyContent: "space-between",
    flexDirection: "row",
    alignItems: "center",
    borderTopLeftRadius: 4,
    borderTopRightRadius: 4,
    backgroundColor: "#F9D63B",
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
    marginTop: 15,
  },

  contentWrap: {
    backgroundColor: "white",
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
  },
  itemWrap: {
    justifyContent: "space-between",
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 6,
  },
  btn: {
    width: 80,
    height: 40,
    ...commonStyles.center,
    backgroundColor: "#F9D63B",
    borderRadius: 5,
  },
  selectWarp: {
    position: "absolute",
    right: 10,
    top: 80,
    backgroundColor: "white",
  },
  select_item: {
    flexDirection: "row",
    alignItems: "center",
    padding: 10,
  },
  ckWrap: {
    width: 15,
    height: 15,
    marginRight: 5,
  },
});
